<?php
namespace app\api\controller\deerhome\user;

use app\api\controller\deerhome\user\BaseAuth;
use think\Db;
use think\Validate;

/**
 * 订单售后
 */
class OrderRefund extends BaseAuth
{
    public function index(){
        $data=Db::name("deerhome_order_refund")->alias('r')
        ->join("deerhome_order o","o.sn=r.order_sn","left")
        ->field("r.lx,r.price_refund,r.status as tk_status,r.addtime as tk_sq_time,o.sn,o.id,o.item_name,o.item_gg_name,o.price_payed,o.id")
        ->where("r.jz_user_id",$this->_user['id'])
        ->limit(60)->order("r.id desc")->select();
        foreach($data as &$item){
            $item['status_txt']="未知";
            if($item['tk_status']==1){
                $item['status_txt']="处理中";
            }
            if($item['tk_status']==2){
                $item['status_txt']="已退款";
            }
            if($item['tk_status']==3){
                $item['status_txt']="已拒绝";
            }
        }

        $this->ok($data);
    }
    public function sub(){
        $id=$this->request->param("id",0,'intval');
        $arr=[];
        $arr['jz_user_id']=$this->_user['id'];
        $arr['lx']=$this->request->param("lx","",'trim');
        $arr['price']=$this->request->param("price","",'trim');
        $arr['price_refund']=$arr['price'];
        $arr['note']=$this->request->param("note","",'trim');
        $arr['addtime']=date("Y-m-d H:i:s");
      
        if(!in_array($arr['lx'],["仅退款"])){
            $this->err("请选择售后类型");
        }
        if($arr['note']==""){
            $this->err("请填写申请说明");
        }
        if(!preg_match("/^\d{1,}\.?\d{0,2}$/",$arr['price'])){
            $this->err("网络传输错误，请重新进入");
        }
       
       $order=Db::name("deerhome_order")->where("id",$id)->where("jz_user_id",$this->_user['id'])->find();
       if(!$order){
           $this->err("订单不存在");
       }
       if(!in_array($order['status'],[2,3,4,5])){
           $this->err("该笔订单不能申请售后");
       }
       if($order['price_payed']!=$arr['price']){
           $this->err("退款金额异常");
       }
       $arr['order_sn']=$order['sn'];
       $arr['order_old_status']=$order['status'];
       //检查是否已经申请了
       $has=Db::name("deerhome_order_refund")->where("order_sn",$order['sn'])->where("status","<",3)->find();
       if($has){
           $this->err("该笔订单已经申请过售后");
       }
       Db::startTrans();
        try{
            Db::name("deerhome_order")->where("id",$order['id'])->update(['status'=>6]);
            Db::name("deerhome_order_refund")->insert($arr);
            Db::name("deerhome_order_log")->insert([
                'order_id'=>$order['id'],
                'add_time'=>date("Y-m-d H:i:s"),
                'ac_user'=>'用户',
                'note'=>"申请售后：{$arr['note']}"
            ]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->err("请重试".$e->getLine(). $e->getMessage());
        }
       $this->ok("ok");
    }
}
